package com.lcxw.hxzbapi.controller.appcontroller;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.controller.membercontroller.MemberRealization;
import com.lcxw.hxzbapi.tencentim.common.TencentImRealization;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.AesCBCUtil;
import com.lcxw.hxzbcommon.common.RedisUtils;
import com.lcxw.hxzbcommon.common.StringUtil;
import com.lcxw.hxzbcommon.entity.CommonBean;

@RestController
@RequestMapping("/api/user")
@CrossOrigin
@Validated
public class ThirdPartyLoginController {

    private Logger logger = LoggerFactory.getLogger(ThirdPartyLoginController.class);

    @Resource
    YwpdMemberService ywpdMemberService;

    @Resource
    RedisUtils redisUtils;

    @Resource
    MemberRealization memberRealization;

    @Resource
    TencentImRealization tencentImRealization;

    final String APPID = CommonBean.WECHAT_APPID;
    final String SECRET = CommonBean.WECHAT_SECRET;

    @PostMapping("/thirdParty/login")
    public Response thirdPartyLogin(@RequestBody JSONObject requestParams) {
        String code = requestParams.getString("code");
        String lastLogIp = requestParams.getString("ip");
        String longitude = requestParams.getString("longitude");
        String latitude = requestParams.getString("latitude");
        logger.info("第三方登录请求：" + requestParams.toJSONString());

        //获取微信授权信息参数
        JSONObject accessObject = getAccessToken(code);
        String accessToken = accessObject.getString("access_token");
        String openId = accessObject.getString("openid");
        String refreshToken = accessObject.getString("refresh_token");
        long expires_in = accessObject.getLong("expires_in");

        YwpdMember ywpdMember = ywpdMemberService.selectByOpenId(openId);

        if (null != ywpdMember) {
            //判断用户是否被后台注销
            if (1 == ywpdMember.getCancelled()) {
                return Response.common(logger, "user is cancelled.", ErrorCode.LOSE_EFFICACY,
                    "user is cancelled.", null);
            }
            JSONObject data = new JSONObject();
            data.put("verifyTelephone", "false");
            data.put("telephone", ywpdMember.getTelephone());
            data.put("userId", ywpdMember.getUserId());
            //构造token 使用userId和时间戳，生成唯一token
            String tokenKey =
                ywpdMember.getUserId() + ":" + Calendar.getInstance().getTimeInMillis();
            String token = null;
            try {
                token = AesCBCUtil.getInstance().encrypt(tokenKey);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("token编码失败");
            }
            redisUtils
                .string_set("uid:" + ywpdMember.getUserId() + ":token", token, 60 * 60 * 24 * 30);

            ywpdMember.setLastLogIp(lastLogIp);
            ywpdMember.setLongitude(longitude);
            ywpdMember.setLatitude(latitude);
            try {
                ywpdMemberService.updateYwpdMember(ywpdMember);
            } catch (Exception e) {
                e.printStackTrace();
            }

            data.put("token", token);
            return Response.ok(data);
        } else {

            JSONObject data = new JSONObject();
            data.put("verifyTelephone", "true");
            data.put("accessToken", accessToken);
            data.put("openId", openId);
            return Response.ok(data);

        }
    }


    @PostMapping("/thirdParty/relateUser")
    public Response relateUser(@RequestBody JSONObject requestParams) {
        String telephone = requestParams.getString("telephone");
        String accessToken = requestParams.getString("accessToken");
        String openId = requestParams.getString("openId");

        String uri =
            "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid="
                + openId + "&lang=zh_CN";
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(URI.create(uri));

        try {
            YwpdMember ywpdMember = ywpdMemberService.selectYwpdMemberByTelephone(telephone);

            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                StringBuilder builder = new StringBuilder();
                for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
                    builder.append(temp);
                }
                //获取到微信平台的用户信息
                JSONObject object = JSONObject.parseObject(builder.toString().trim());
                String nickname = object.getString("nickname");
                int sex_int = object.getInteger("sex");
                String sex = sex_int == 1 ? "男" : "女";
                String province = object.getString("province");
                String city = object.getString("city");
                String country = object.getString("country");
                String imgUrl = object.getString("headimgurl");

                String userId, setPassword;
                JSONObject data = new JSONObject();

                if (null != ywpdMember) {
                    //手機號碼已經存在，則綁定該手機號和unionId
                    ywpdMember.setOpenId(openId);

                    if (StringUtil.isEmpty(ywpdMember.getNickName())) {
                        ywpdMember.setNickName(nickname);
                    }
                    if (StringUtil.isEmpty(ywpdMember.getSex())) {
                        ywpdMember.setSex(sex);
                    }
                    if (StringUtil.isEmpty(ywpdMember.getProvince())) {
                        ywpdMember.setProvince(province);
                    }
                    if (StringUtil.isEmpty(ywpdMember.getCity())) {
                        ywpdMember.setCity(city);
                    }
                    if (StringUtil.isEmpty(ywpdMember.getImgUrl())) {
                        ywpdMember.setImgUrl(imgUrl);
                    }

                    ywpdMemberService.updateYwpdMember(ywpdMember);
                    userId = ywpdMember.getUserId() + "";
                    //告诉前端是否还需要设置密码
                    setPassword = "false";
                    String token = memberRealization.genToken(userId);
                    data.put("userId", ywpdMember.getUserId());
                    data.put("token", token);
                } else {
                    //手機號碼不存在，則新建一個用戶
                    YwpdMember newMember = new YwpdMember();

                    newMember.setNickName(nickname);
                    newMember.setSex(sex);
                    newMember.setProvince(province);
                    newMember.setCity(city);
                    newMember.setImgUrl(imgUrl);
                    newMember.setOpenId(openId);
                    newMember.setTelephone(telephone);
                    newMember.setPassword("123456");

                    Response register = ywpdMemberService.register(newMember);
                    Map registerData = (Map) register.getData();
                    //告诉前端是否还需要设置密码
                    setPassword = "true";
                    data.put("userId", registerData.get("userId"));
                    data.put("token", registerData.get("token"));

                    //将新用户的信息同步到腾讯的IM系统
                    JSONObject imBody = new JSONObject();
                    imBody.put("From_Account", registerData.get("userId") + "");
                    List<JSONObject> profileItem = new ArrayList<>();

                    JSONObject p1_nickName = new JSONObject();
                    p1_nickName.put("Tag", "Tag_Profile_IM_Nick");
                    p1_nickName.put("value", nickname);
                    profileItem.add(p1_nickName);

                    JSONObject p2_sex = new JSONObject();
                    p2_sex.put("Tag", "Tag_Profile_IM_Gender");
                    String imSex;
                    if (sex_int == 1) {
                        imSex = "Gender_Type_Male";
                    } else if (sex_int == 2) {
                        imSex = "Gender_Type_Female";
                    } else {
                        imSex = "Gender_Type_Unknown";
                    }
                    p2_sex.put("value", imSex);
                    profileItem.add(p2_sex);

                    JSONObject p3_imgUrl = new JSONObject();
                    p3_imgUrl.put("Tag", "Tag_Profile_IM_Image");
                    p3_imgUrl.put("value", imgUrl);
                    profileItem.add(p3_imgUrl);

                    imBody.put("ProfileItem", profileItem);
                    tencentImRealization.updateImUserInfo(imBody);
                }

                data.put("setPassword", setPassword);

                return Response.ok(data);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Response.ok();

    }


    /**
     * accessToken = object.getString("access_token"); openID = object.getString("openid");
     * refreshToken = object.getString("refresh_token"); expires_in = object.getLong("expires_in");
     * unionId = accessObject.getString("unionid");
     */
    public JSONObject getAccessToken(String code) {

        String url =
            "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + SECRET
                + "&code=" + code + "&grant_type=authorization_code";
        URI uri = URI.create(url);
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(uri);
        HttpResponse response;

        try {
            response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();

                BufferedReader reader = new BufferedReader(
                    new InputStreamReader(entity.getContent(), "UTF-8"));
                StringBuilder sb = new StringBuilder();

                for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
                    sb.append(temp);
                }

                return JSONObject.parseObject(sb.toString().trim());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}
